<template>
  <div class="avue-top">
    <div class="top-bar__left">
      <div class="avue-breadcrumb"
           :class="[{ 'avue-breadcrumb--active': isCollapse }]"
           v-if="showCollapse">
        <i class="icon-navicon"
           @click="setCollapse"></i>
      </div>
    </div>
    <div class="top-bar__title">
      <div class="top-bar__item top-bar__item--show"
           v-if="showMenu">
        <top-menu></top-menu>
      </div>
      <span class="top-bar__item"
            v-if="showSearch">
        <top-search></top-search>
      </span>
    </div>
    <div class="top-bar__right">
      <el-tooltip v-if="userInfo.authority==='store'"
                  effect="dark"
                  content="消息"
                  placement="bottom">
        <div class="top-bar__item">
          <el-badge :value="badge" class="item">
          <el-button icon="el-icon-loading" circle
                     @click="openDialogVisible">
          </el-button>
          </el-badge>
        </div>
      </el-tooltip>

      <el-tooltip v-if="showColor"
                  effect="dark"
                  :content="$t('navbar.color')"
                  placement="bottom">
        <div class="top-bar__item">
          <top-color></top-color>
        </div>
      </el-tooltip>
      <el-tooltip v-if="showDebug"
                  effect="dark"
                  :content="logsFlag?$t('navbar.bug'):logsLen+$t('navbar.bugs')"
                  placement="bottom">
        <div class="top-bar__item">
          <top-logs></top-logs>
        </div>
      </el-tooltip>
      <el-tooltip v-if="showLock"
                  effect="dark"
                  :content="$t('navbar.lock')"
                  placement="bottom">
        <div class="top-bar__item">
          <top-lock></top-lock>
        </div>
      </el-tooltip>
      <el-tooltip v-if="showTheme"
                  effect="dark"
                  :content="$t('navbar.theme')"
                  placement="bottom">
        <div class="top-bar__item top-bar__item--show">
          <top-theme></top-theme>
        </div>
      </el-tooltip>
      <el-tooltip effect="dark"
                  :content="$t('navbar.language')"
                  placement="bottom">
        <div class="top-bar__item top-bar__item--show">
          <top-lang></top-lang>
        </div>
      </el-tooltip>
      <el-tooltip v-if="showFullScren"
                  effect="dark"
                  :content="isFullScren?$t('navbar.screenfullF'):$t('navbar.screenfull')"
                  placement="bottom">
        <div class="top-bar__item">
          <i :class="isFullScren?'icon-tuichuquanping':'icon-quanping'"
             @click="handleScreen"></i>
        </div>
      </el-tooltip>
      <img class="top-bar__img"
           :src="userInfo.avatar">
      <el-dropdown>
        <span class="el-dropdown-link">
          {{userInfo.userName}}
          <i class="el-icon-arrow-down el-icon--right"></i>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>
            <router-link to="/">{{$t('navbar.dashboard')}}</router-link>
          </el-dropdown-item>
          <el-dropdown-item>
            <router-link to="/info/index">{{$t('navbar.userinfo')}}</router-link>
          </el-dropdown-item>
          <el-dropdown-item @click.native="logout"
                            divided>{{$t('navbar.logOut')}}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      title="聊天窗口"
      :visible.sync="dialogVisible"
      width="43%"
      :before-close="handleClose">
      <div class="talk_con">
        <div class="talk_show" id="talk_show">
          <el-alert
            v-if="this.message.length===0"
            style="margin-top: 30%"
            title="暂时没有消息哦!"
            type="success"
            center
            :closable="false">
          </el-alert>
          <div v-if="this.message.length!==0">
            <div v-for="(msg , index) in message" :key='index'>
              <div v-if="msg.sendId===userInfo.userId" class="btalk">
                <span>{{msg.msg}}</span><img v-if="msg.sendImg" style="width: 40px; height: 40px;border-radius:50%"
                                             :src="msg.sendImg" alt="无"></div>
              <div v-if="msg.sendId!==userInfo.userId" class="atalk">
                <img v-if="msg.sendImg" style="width: 40px; height: 40px;border-radius:50%"
                     :src="msg.sendImg" alt="无">
                <span>{{msg.msg}}</span></div>
            </div>
          </div>
        </div>
        <div class="talk_input">
          <input type="text" class="talk_word" v-model="textarea">
          <input type="button" v-if="this.message.length!==0" value="发送" class="talk_sub" id="talksub" @click="send">
          <input type="button" value="关闭" class="talk_sub"  @click="dialogVisible = false">
          <input type="button" v-if="this.message.length!==0" value="清空" class="talk_sub"  @click="closeChat">
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters, mapState } from "vuex";
import { fullscreenToggel, listenfullscreen } from "@/util/util";
import topLock from "./top-lock";
import topMenu from "./top-menu";
import topSearch from "./top-search";
import topTheme from "./top-theme";
import topLogs from "./top-logs";
import topColor from "./top-color";
import topLang from "./top-lang";
import {removeWebSocket,loginWebSocket} from "@/api/user";
import {sendChatWebSocket} from "@/api/websocket";
import {validate} from "@/util/validate";

export default {
  components: {
    topLock,
    topMenu,
    topSearch,
    topTheme,
    topLogs,
    topColor,
    topLang,
  },
  name: "top",
  data() {
    return {
      dialogVisible:false,
      message:[],
      textarea:'',
      badge:'',
    };
  },
  filters: {},
  created() {},
  mounted() {
    listenfullscreen(this.setScreen);
    this.loginSocket();
    // WebSocket
    if ('WebSocket' in window) {
      this.websocket = new WebSocket('ws://localhost:7777/websocket/' + this.userInfo.userId)
      this.initWebSocket()
    } else {
      alert('当前浏览器不支持!')
    }
  },

  beforeDestroy () {
    this.onbeforeunload()
  },

  computed: {
    ...mapState({
      showDebug: state => state.common.showDebug,
      showTheme: state => state.common.showTheme,
      showLock: state => state.common.showLock,
      showFullScren: state => state.common.showFullScren,
      showCollapse: state => state.common.showCollapse,
      showSearch: state => state.common.showSearch,
      showMenu: state => state.common.showMenu,
      showColor: state => state.common.showColor
    }),
    ...mapGetters([
      "userInfo",
      "isFullScren",
      "tagWel",
      "tagList",
      "isCollapse",
      "tag",
      "logsLen",
      "logsFlag"
    ])
  },
  watch:{
    //监听盒子高度 让新信息处于最低部
    message:function () {
      this.$nextTick(() => {
        this.$nextTick(() => {
          let msg = document.getElementById('talk_show');// 获取对象
          if (msg===null){
            return
          }
          msg.scrollTop = msg.scrollHeight // 滚动高度
        })
      });
    }
  },
  methods: {
    closeChat(){
      this.message =[];
    },
    send(){
      if (validate(this.textarea)){
        var row={
          receiveId:this.message[0].sendId,
          sendId: this.userInfo.userId,
          sendImg:this.userInfo.avatar,
          msg:this.textarea
        }
        sendChatWebSocket(row).then(() => {
          this.message.push(row)
        });
      }else {
        this.$message.error('不能发空信息哦!');
      }
      this.textarea = ''
    },
    openDialogVisible(){
      this.dialogVisible =true
      this.badge = ''
    },

    loginSocket(){
      const id = this.userInfo.userId;
      loginWebSocket(id).then((res) => {
        const msg = res.data.data;
        if (JSON.stringify(msg)!=='{}'){
          this.$notify.success({
            title: '提示',
            message: msg,
            duration: 0,
            offset: 100,
            onClose:()=>{
              const id = this.userInfo.userId;
              removeWebSocket(id).then(() => {
              })
            }
          });
        }
      })
    },
    initWebSocket () {
      // 连接错误
      this.websocket.onerror = this.setErrorMessage
      // 连接成功
      this.websocket.onopen = this.setOnopenMessage

      // 收到消息的回调
      this.websocket.onmessage = this.setOnmessageMessage

      // 连接关闭的回调
      this.websocket.onclose = this.setOncloseMessage

      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = this.onbeforeunload
    },
    setErrorMessage () {
      console.log('WebSocket连接发生错误 状态码：' + this.websocket.readyState)
    },
    setOnopenMessage () {
      console.log(this.userInfo.userName+'WebSocket连接成功    状态码：' + this.websocket.readyState)
    },
    setOnmessageMessage (event) {
      const datas = JSON.parse(event.data);
      // 根据服务器推送的消息做自己的业务处理
      if (datas.type==='订单推送'){
      //console.log('服务端返回：' + datas)
      this.$notify.success({
        title: '提示',
        message: datas.msg,
        duration: 0,
        offset: 100,
        onClose:()=>{
          const id = this.userInfo.userId;
          removeWebSocket(id).then(() => {
          })
        }
      });
      }else {
        if (!this.dialogVisible){
          this.badge = 'new'
        }
        this.message.push(datas)
      }
    },

    setOncloseMessage () {
      console.log(this.userInfo.userName+'WebSocket连接关闭    状态码：' + this.websocket.readyState)
    },
    onbeforeunload () {
      this.closeWebSocket()
    },
    closeWebSocket () {
      this.websocket.close()
    },
    handleScreen() {
      fullscreenToggel();
    },
    setCollapse() {
      this.$store.commit("SET_COLLAPSE");
    },
    setScreen() {
      this.$store.commit("SET_FULLSCREN");
    },
    logout() {
      this.$confirm(this.$t("logoutTip"), this.$t("tip"), {
        confirmButtonText: this.$t("submitText"),
        cancelButtonText: this.$t("cancelText"),
        type: "warning"
      }).then(() => {
        this.$store.dispatch("LogOut").then(() => {
          this.$router.push({ path: "/login" });
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
  .talk_con {
    width: 90%;
    height: 500px;
    border: 1px solid #666;
    margin-top: -5% ;
    background: #f9f9f9;
  }

  .talk_show {
    width: 90%;
    height: 420px;
    border: 1px solid #666;
    background: #fff;
    margin: 10px auto 0;
    overflow: auto;
  }

  .talk_input {
    width: 90%;
    margin: 10px auto 0;
  }
  .talk_word {
    width: 47%;
    height: 26px;
    padding: 0px;
    float: left;
    margin-left: 10px;
    outline: none;
    text-indent: 10px;
  }
  .talk_sub {
    width: 56px;
    height: 30px;
    float: left;
    margin-left: 10px;
  }

  .atalk span {
    display: inline-block;
    background: #0181cc;
    border-radius: 10px;
    color: #fff;
    padding: 5px 10px;
  }

  .btalk {
    margin: 10px;
    text-align: right;
  }

  .btalk span {
    display: inline-block;
    background: #ef8201;
    border-radius: 10px;
    color: #fff;
    padding: 5px 10px;
  }

  .mailTable {
    width: 100%;
    border-top: 1px solid #E6EAEE;
    border-left: 1px solid #E6EAEE;
  }

  .mailTable tr td {
    width: 200px;
    height: 35px;
    line-height: 35px;
    box-sizing: border-box;
    padding: 0 10px;
    border-bottom: 1px solid #E6EAEE;
    border-right: 1px solid #E6EAEE;
  }

  .mailTable tr td.column {
    background-color: #EFF3F6;
    color: #393C3E;
    width: 30%;
  }
</style>
